<template>
  <TopNav />
  <div :class="['essay-editor', theme]">
    <!-- <header class="header">
      <div class="container">
        <h1>AI 作文修改助手</h1>
        <div class="theme-switcher">
          <button class="theme-btn light" :class="{ active: theme === 'light' }" @click="setTheme('light')">
            ☀️ 亮色
          </button>
          <button class="theme-btn dark" :class="{ active: theme === 'dark' }" @click="setTheme('dark')">
            🌙 暗色
          </button>
        </div>
      </div>
    </header> -->

    <main class="main-content">
      <div class="container">
        <div class="editor-container">
          <!-- 原文输入区 -->
          <section class="original-section">
            <div class="section-header">
              <h2>原文输入</h2>
              <div class="word-count">字数: {{ originalWordCount }}</div>
            </div>
            <textarea v-model="originalText" class="essay-textarea" placeholder="在这里粘贴或输入您的作文..."
              @input="countOriginalWords"></textarea>
            <div class="action-buttons">
              <button class="btn analyze-btn" :disabled="!originalText.trim() || isLoading" @click="submitEssay">
                <span v-if="!isLoading">AI 分析修改</span>
                <span v-else class="loading">
                  <span class="spinner"></span> 处理中...
                </span>
              </button>
              <button class="btn clear-btn" @click="clearText">
                清空文本
              </button>
            </div>
          </section>

          <!-- 修改结果区 -->
          <section class="result-section" :class="{ 'has-result': modifiedEssay }">
            <div class="section-header">
              <h2>AI 修改建议</h2>
              <div class="word-count" v-if="modifiedEssay">
                字数: {{ improvedWordCount }} ({{ wordCountDifference }})
              </div>
            </div>
            <div class="result-content" v-if="modifiedEssay">
              <div class="improved-text" v-html="modifiedEssay"></div>
              <div class="feedback" v-if="feedback">
                <h3>反馈建议</h3>
                <p>{{ feedback }}</p>
              </div>
              <div class="result-actions">
                <button class="btn copy-btn" @click="copyResult">
                  📋 复制结果
                </button>
                <button class="btn save-btn" @click="saveEssay">
                  💾 保存作文
                </button>
              </div>
            </div>
            <div class="empty-result" v-else>
              <div class="placeholder-icon">✍️</div>
              <p>AI 修改结果将显示在这里</p>
              <p class="hint" v-if="isLoading">AI正在分析您的作文，请稍候...</p>
            </div>
          </section>
        </div>

        <!-- 修改建议详情 -->
        <section class="suggestions-section" v-if="suggestions.length > 0">
          <h2>详细修改建议</h2>
          <div class="suggestions-list">
            <div v-for="(suggestion, index) in suggestions" :key="index" class="suggestion-item">
              <div class="suggestion-type">{{ suggestion.type }}</div>
              <div class="suggestion-content">
                <div class="original-part">
                  <strong>原文:</strong> {{ suggestion.original }}
                </div>
                <div class="suggested-part">
                  <strong>建议:</strong> {{ suggestion.suggested }}
                </div>
                <div class="explanation" v-if="suggestion.explanation">
                  {{ suggestion.explanation }}
                </div>
              </div>
            </div>
          </div>
        </section>
      </div>
    </main>

    <footer class="footer">
      <div class="container">
        <p>© 2025 AI 作文修改助手 - 提升您的写作水平</p>
      </div>
    </footer>
  </div>
</template>

<script setup>
import TopNav from "../../components/TopNav.vue";
import { ref, computed, inject } from 'vue'
import { marked } from 'marked' // 用于Markdown渲染

// 主题功能
const theme = inject('theme')

// const setTheme = inject('setTheme')
const setTheme = async (newTheme) => {
  theme.value = newTheme
}

// 作文数据
const originalText = ref('')
const modifiedEssay = ref('')
const feedback = ref('')
const originalWordCount = ref(0)
const improvedWordCount = ref(0)
const isLoading = ref(false)
const suggestions = ref([])
import getAiResponse from "../../api/getAi.js"
// 模拟AI API调用
const getAiResponsekkk = async (messages) => {
  // 这里应该是实际的API调用
  // 以下是模拟实现
  return new Promise((resolve) => {
    setTimeout(() => {
      const essay = originalText.value
      resolve({
        content: `**修改后的作文:**\n\n${essay
          .replace(/\bgood\b/gi, 'excellent')
          .replace(/\bbad\b/gi, 'poor')
          .replace(/\bvery\b/gi, 'extremely')
          .replace(/\.\s*\bI\b/g, '. I')
          .replace(/\bthing\b/gi, match =>
            ['aspect', 'element', 'factor', 'component'][Math.floor(Math.random() * 4)]
          )
          }\n\n**AI建议:**\n- 文章结构清晰，但可以增加更多细节和例子来支持论点\n- 部分词汇可以升级为更专业的表达\n- 注意第三人称单数动词形式`,
        feedback: "AI已对作文进行了优化，主要改进了词汇选择和语法结构。建议关注标点符号的使用和段落衔接。"
      })
    }, 1500)
  })
}

// 提交作文给AI修改
const submitEssay = async () => {
  if (!originalText.value.trim()) {
    alert("请输入作文内容！")
    return
  }

  isLoading.value = true
  modifiedEssay.value = ""
  feedback.value = ""
  suggestions.value = []

  const messages = [
    {
      role: "user",
      content: `请修改以下作文：\n${originalText.value}\n\n要求：
1. 返回修改后的文章
2. 指出主要的修改点
3. 提供改进建议
4. 如果有语法错误请纠正`
    }
  ]

  try {
    const response = await getAiResponse(messages)
    console.log("AI响应:", response)

    if (response) {
      modifiedEssay.value = marked(response.content || "修改失败")
      feedback.value = response.feedback || "AI提供了优化建议，请查看修改后的作文。"
      improvedWordCount.value = countWords(
        modifiedEssay.value.replace(/<[^>]*>/g, '') // 去除HTML标签统计字数
      )

      // 解析建议
      parseSuggestions(response.content)
    } else {
      alert("获取修改结果失败，请稍后重试")
    }
  } catch (error) {
    console.error("修改请求失败:", error)
    alert("修改过程中出现错误，请重试")
  } finally {
    isLoading.value = false
  }
}

// 解析AI返回的建议
const parseSuggestions = (content) => {
  // 这里应该是根据AI返回内容解析具体建议
  // 以下是模拟实现
  suggestions.value = [
    {
      type: '词汇提升',
      original: 'good',
      suggested: 'excellent',
      explanation: '"excellent"更能表达强烈的正面评价'
    },
    {
      type: '语法修正',
      original: 'He go to school.',
      suggested: 'He goes to school.',
      explanation: '主语为第三人称单数，动词需加"s"'
    },
    {
      type: '句式优化',
      original: 'This is a book. It is interesting.',
      suggested: 'This is an interesting book.',
      explanation: '合并简单句使表达更紧凑'
    }
  ]
}

// 字数统计
const countOriginalWords = () => {
  originalWordCount.value = countWords(originalText.value)
}

const countWords = (text) => {
  return text.trim() ? text.trim().split(/\s+/).length : 0
}

// 清空文本
const clearText = () => {
  originalText.value = ''
  modifiedEssay.value = ''
  feedback.value = ''
  originalWordCount.value = 0
  improvedWordCount.value = 0
  suggestions.value = []
}

// 复制结果
const copyResult = async () => {
  if (!modifiedEssay.value) return
  try {
    // 创建一个临时div来提取纯文本
    const tempDiv = document.createElement('div')
    tempDiv.innerHTML = modifiedEssay.value
    const plainText = tempDiv.textContent || tempDiv.innerText || ''

    await navigator.clipboard.writeText(plainText)
    alert('已复制到剪贴板!')
  } catch (err) {
    console.error('复制失败:', err)
    alert('复制失败，请手动选择文本复制')
  }
}

// 保存作文
const saveEssay = () => {
  if (!modifiedEssay.value) return
  const essayData = {
    original: originalText.value,
    modified: modifiedEssay.value,
    feedback: feedback.value,
    suggestions: suggestions.value,
    date: new Date().toISOString()
  }
  console.log('保存作文:', essayData)
  alert('作文已保存! (查看控制台了解数据格式)')
}

// 计算属性
const wordCountDifference = computed(() => {
  const diff = improvedWordCount.value - originalWordCount.value
  return diff > 0 ? `+${diff}` : diff
})
</script>

<style scoped>
/* 变量定义 */
:root,
.light {
  --bg-color: #f8f9fa;
  --text-color: #212529;
  --primary-color: #4361ee;
  --secondary-color: #3f37c9;
  --accent-color: #4895ef;
  --card-bg: #ffffff;
  --header-bg: #4361ee;
  --header-text: #ffffff;
  --border-color: #dee2e6;
  --hover-color: #e9ecef;
  --success-color: #4cc9f0;
  --warning-color: #f72585;
  --highlight-color: #fff3cd;
  --feedback-bg: #f8f9fa;
}

.dark {
  --bg-color: #121212;
  --text-color: #e0e0e0;
  --primary-color: #3a86ff;
  --secondary-color: #2667cc;
  --accent-color: #8338ec;
  --card-bg: #1e1e1e;
  --header-bg: #1a1a2e;
  --header-text: #ffffff;
  --border-color: #333333;
  --hover-color: #2d2d2d;
  --success-color: #4cc9f0;
  --warning-color: #f72585;
  --highlight-color: #333300;
  --feedback-bg: #252525;
}

/* 基础样式 */
.essay-editor {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: var(--bg-color);
  color: var(--text-color);
  transition: background-color 0.3s, color 0.3s;
}

.container {
  width: 100%;
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 头部样式 */
.header {
  background-color: var(--header-bg);
  color: var(--header-text);
  padding: 1rem 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.header .container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.theme-switcher {
  display: flex;
  gap: 0.5rem;
}

.theme-btn {
  padding: 0.5rem 1rem;
  border-radius: 5px;
  border: none;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
}

.theme-btn.light {
  background-color: #f8f9fa;
  color: #212529;
}

.theme-btn.dark {
  background-color: #343a40;
  color: #f8f9fa;
}

.theme-btn.active {
  transform: scale(1.05);
  box-shadow: 0 0 0 2px var(--accent-color);
}

/* 主要内容样式 */
.main-content {
  flex: 1;
  padding: 2rem 0;
}

.editor-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2rem;
  margin-bottom: 2rem;
}

@media (max-width: 992px) {
  .editor-container {
    grid-template-columns: 1fr;
  }
}

/* 文本区域样式 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.word-count {
  font-size: 0.9rem;
  color: var(--secondary-color);
  font-weight: 500;
}

.essay-textarea {
  width: 96%;
  min-height: 300px;
  padding: 2%;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  background-color: var(--card-bg);
  color: var(--text-color);
  font-size: 1rem;
  line-height: 1.6;
  resize: vertical;
  transition: border-color 0.3s;
}

.essay-textarea:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.2);
}

/* 按钮样式 */
.action-buttons {
  display: flex;
  gap: 1rem;
  margin-top: 1rem;
}

.btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.analyze-btn {
  background-color: var(--primary-color);
  color: white;
  flex: 1;
}

.analyze-btn:hover:not(:disabled) {
  background-color: var(--secondary-color);
}

.clear-btn {
  background-color: var(--card-bg);
  color: var(--text-color);
  border: 1px solid var(--border-color);
}

.clear-btn:hover {
  background-color: var(--hover-color);
}

.loading {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.spinner {
  width: 1rem;
  height: 1rem;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 结果区域样式 */
.result-section {
  background-color: var(--card-bg);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  padding: 1rem;
  display: flex;
  flex-direction: column;
}

.empty-result {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--secondary-color);
  min-height: 300px;
}

.placeholder-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.hint {
  margin-top: 1rem;
  font-size: 0.9rem;
  color: var(--secondary-color);
}

.has-result {
  border-color: var(--primary-color);
}

.improved-text {
  flex: 1;
  padding: 1rem;
  background-color: var(--card-bg);
  border-radius: 8px;
  line-height: 1.6;
  overflow-y: auto;
  max-height: 300px;
}

.improved-text :deep(p) {
  margin-bottom: 1rem;
}

.improved-text :deep(strong) {
  color: var(--primary-color);
}

.feedback {
  margin-top: 1rem;
  padding: 1rem;
  background-color: var(--feedback-bg);
  border-radius: 8px;
}

.feedback h3 {
  margin-top: 0;
  color: var(--primary-color);
}

.result-actions {
  display: flex;
  gap: 1rem;
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid var(--border-color);
}

.copy-btn {
  background-color: var(--success-color);
  color: white;
}

.save-btn {
  background-color: var(--accent-color);
  color: white;
}

/* 建议区域样式 */
.suggestions-section {
  margin-top: 2rem;
}

.suggestions-list {
  display: grid;
  gap: 1rem;
}

.suggestion-item {
  background-color: var(--card-bg);
  border-radius: 8px;
  padding: 1rem;
  border-left: 4px solid var(--primary-color);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.suggestion-type {
  font-weight: bold;
  color: var(--primary-color);
  margin-bottom: 0.5rem;
}

.original-part {
  color: var(--warning-color);
  margin-bottom: 0.25rem;
}

.suggested-part {
  color: var(--success-color);
  margin-bottom: 0.25rem;
}

.explanation {
  font-size: 0.9rem;
  color: var(--secondary-color);
  margin-top: 0.5rem;
}

/* 页脚样式 */
.footer {
  background-color: var(--header-bg);
  color: var(--header-text);
  padding: 1rem 0;
  text-align: center;
  font-size: 0.9rem;
}

/* 响应式调整 */
@media (max-width: 576px) {

  .action-buttons,
  .result-actions {
    flex-direction: column;
  }

  .btn {
    width: 100%;
  }
}
</style>